# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : process_alarm_count_view.py
# Time       ：2023/11/2 15:55
# Author     ：YangYong
# version    ：python 3.10
# Description：流程告警
"""
from flask_restx import Resource, fields
from sqlalchemy import func

from apis.notice.model.alarm import Alarm
from apis.data_screen import data_screen_ns
from apis.data_screen.schema.process_alarm_count_schema import ProcessAlarmCountSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel

process_alarm = {
    'name': fields.String(description='告警名称'),
    'value': fields.String(description='告警数量'),
    'percentage': fields.String(description='使用比例'),
    'maxValue': fields.String(description='告警总量'),

}

process_alarm_marshal = MarshalModel('process_alarm', data_screen_ns)


class ProcessAlarmCountView(Resource):
    url = '/process_alarm'

    def __init__(self, *args, **kwargs):
        super(ProcessAlarmCountView, self).__init__(*args, **kwargs)
        self.total = 0

    @handle_api_error()
    @data_screen_ns.doc(description='获取流程告警')
    @data_screen_ns.marshal_with(process_alarm_marshal.list_response(process_alarm, True, False))
    def get(self):
        """获取流程告警"""
        response_data = list()
        objs = db.session.query(
            func.count(1).label('value'), Alarm.process_name.label('name')
        ).filter(Alarm.active == 1).group_by('name').all()
        info = ProcessAlarmCountSchema().dump(objs, many=True)
        for item in info:
            self.total = self.total + item.get('value') or 0

        for item in info:
            response_data.append(
                {
                    'name': item.get('name'),
                    'value': item.get('value'),
                    'percentage': f"{round(item.get('value') / self.total * 100)}%",
                    'maxValue': self.total
                }
            )

        response_data.sort(key=lambda val: val.get('value'), reverse=True)
        return generate_response(response_data[0:5])
